<?php
	namespace ampleharvest\task;
	use\ampleharvest\code;

	require_once dirname(dirname(dirname(__FILE__))) . '/config/cConfig.php';
	$codeConfig = new \ampleharvest\code\cConfig();
	
	require_once dirname(dirname(dirname(__FILE__))) . "/abstract_classes/abs_Task.php";
	require_once dirname(dirname(dirname(__FILE__))) . "/classes/Tables/cTABLE_Saved_Queries.php";
	require_once dirname(dirname(dirname(__FILE__))) . "/classes/cScheduler.php";
	require_once dirname(dirname(dirname(__FILE__))) . "/classes/notification/query_Notification/cQueryNotification.php";
	require_once dirname(dirname(dirname(__FILE__))) . "/classes/search/cResults.php";
	require_once dirname(dirname(dirname(__FILE__))) . "/classes/search/solr/cSolr.php";

	
	require_once $codeConfig->C_STR_USER_MANAGER_PATH . '/Classes/cTABLE_Users.php';

	class scheduled_Queries extends \abs_Task
	{
		const C_STR_NAME = "scheduled_Queries";

		public function __construct($str_LockPath)
		{
			ini_set("memory_limit", "250M");
			$this->set_LockPath($str_LockPath);
			$this->set_Name(self::C_STR_NAME);
			parent::__construct();
		}

		public function run($bool_Force = false)
		{
			$this->set_Force($bool_Force);
			if (!parent::run())
			{
				return false;
			}

			$obj_Now = new \DateTime();
			$obj_MailNotification = null;
			$obj_Solr = null;
			$obj_Results = null;
			$obj_Template = null;
			$obj_TABLE_SavedQueries = new \cTABLE_Saved_Queries();
			$str_IndexedDateKey = "index_date";

			$obj_TABLE_SavedQueries->clear_Query();
			$obj_TABLE_SavedQueries->add_ColumnQuery($obj_TABLE_SavedQueries->m_int_COL_NextRun, $obj_Now->format("Y-m-d H:i:s"), \cCondition::c_str_OPERATOR_LESS);
			$obj_TABLE_SavedQueries->add_ColumnQuery($obj_TABLE_SavedQueries->m_int_COL_Schedule, 1);
			$int_Items = $obj_TABLE_SavedQueries->do_Search();

			$m_obj_SolrServer = new \ampleharvest\code\search\cResults();

			$this->log("Processing $int_Items Queries.");

			//print("Processing $int_Items\n");

			$m_obj_SolrServer->set_Solr(new \cSolr(null, null, null));
			$this->output_Error("Using default solr instance -- scheduled_Queries");
			

			foreach ($obj_TABLE_SavedQueries->get_ResultSet() as $obj_Query)
			{
				$m_obj_SolrServer->clear_Query();

				$obj_MailNotification = new \cQueryNotification();

				$obj_TABLE_SavedQueries->load_DataFromArray($obj_Query);

				$this->log("Processing Stored Query " . $obj_TABLE_SavedQueries->get_id() . ".",
					\cAmpleHarvestLog::C_INT_LEVEL_DEBUG);

				if (!$obj_TABLE_SavedQueries->get_q_string())
				{
					$this->log_Error($obj_TABLE_SavedQueries->get_id() . " has no query string.");
					continue;
				}

				if (!$obj_TABLE_SavedQueries->get_user_id())
				{
					$this->log_Error($obj_TABLE_SavedQueries->get_id() . " has no User ID.");
					continue;
				}

				$obj_LastRun = new \DateTime($obj_TABLE_SavedQueries->get_ColumnData($obj_TABLE_SavedQueries->m_int_COL_LastRun));

				$obj_Query = \cTABLE_Saved_Queries::decode($obj_TABLE_SavedQueries->get_q_string());

				if (!isset($obj_Query->Query))
				{
					$this->log_Error($obj_TABLE_SavedQueries->get_id() . " has no Query in its query string.");
					continue;
				}

				if (!$m_obj_SolrServer->set_QueryFromJson($obj_Query))
				{
					$this->log_Error($obj_TABLE_SavedQueries->get_id() . " does not contain a vailid query object.");
					continue;
				}
				if (!empty($obj_LastRun))
				{
					$m_obj_SolrServer->add_Query(\cSolr::C_STR_KEY_INDEX_DATE, "[" . $obj_LastRun->format(\cSolr::C_STR_FORMAT_DATE) . " TO *]");
				}

				$str_UserEmail = $this->get_UserEmail($obj_TABLE_SavedQueries->get_ColumnData($obj_TABLE_SavedQueries->m_int_COL_UserID));

				if (!$str_UserEmail)
				{
					$this->log_Error($obj_TABLE_SavedQueries->get_id() . "'s User Has no Email Address.");
					continue;
				}

				$m_obj_SolrServer->set_Page(0);

				$m_obj_SolrServer->set_PerPage($obj_TABLE_SavedQueries->get_max());

				$m_obj_SolrServer->set_DisplayFields(array("*", "score"));
				$m_obj_SolrServer->set_UserID($obj_TABLE_SavedQueries->get_user_id());

				ob_start();
				//print("Check " . __LINE__ . "\n");
				$m_obj_SolrServer->output_ResultsAsHTML();
				//print("Check " . __LINE__ . "\n");
				$str_Output = ob_get_clean();

				$this->log($obj_TABLE_SavedQueries->get_id() . " returned" . $m_obj_SolrServer->get_Total() . " results.",
					\cAmpleHarvestLog::C_INT_LEVEL_DEBUG);
					
				$obj_MailNotification->set_Body($str_Output);

				$obj_MailNotification->add_To($str_UserEmail);
				$obj_MailNotification->set_Subject("Query Results for - " . $obj_TABLE_SavedQueries->get_q_title() . " (" . $obj_Now->format("d/M/Y H:00 T") . ")");

				$obj_MailNotification->send();

				$obj_TABLE_SavedQueries->set_ColumnValue($obj_TABLE_SavedQueries->m_int_COL_LastRun, $obj_Now->format("Y-m-d H:i:s"));

				$obj_Scheduler = new \cScheduler($obj_TABLE_SavedQueries->get_t_hour(),
					$obj_TABLE_SavedQueries->get_t_day(),
					$obj_TABLE_SavedQueries->get_t_dayofweek(),
					$obj_TABLE_SavedQueries->get_t_month());

				$obj_TABLE_SavedQueries->set_next_run($obj_Scheduler->get_Next()->format("Y-m-d H:i:s"));

				$obj_TABLE_SavedQueries->save_Data2DB();
			}
		}

		protected function get_UserEmail($str_UserID)
		{
			$obj_TABLE_Users = new \cTABLE_Users();

			$obj_TABLE_Users->load_DataFromUserID($str_UserID);

			return $obj_TABLE_Users->get_ColumnData($obj_TABLE_Users->m_int_COL_Email1);
		}
	}
?>